<template>
    <div class="location-selector">
      <!-- 库位选择对话框 -->
      <el-dialog :title="title" v-model="visible" width="800px" append-to-body>
        <!-- 搜索区域 -->
        <el-form :model="queryParams" :inline="true">
          <el-form-item label="仓库">
            <el-select v-model="queryParams.warehouseId" placeholder="请选择仓库" @change="handleWarehouseChange">
              <el-option
                v-for="item in warehouseOptions"
                :key="item.warehouseId"
                :label="item.warehouseName"
                :value="item.warehouseId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="库位编号">
            <el-input v-model="queryParams.locationCode" placeholder="请输入库位编号" />
          </el-form-item>
          <el-form-item label="库位名称">
            <el-input v-model="queryParams.locationName" placeholder="请输入库位名称" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getLocationList">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        
        <!-- 库位列表 -->
        <el-table :data="locationList" @row-click="handleLocationSelect" v-loading="loading" highlight-current-row>
          <el-table-column label="库位编号" prop="locationCode" width="120" />
          <el-table-column label="库位名称" prop="locationName" width="150" />
          <el-table-column label="所属仓库" prop="warehouseName" width="150" />
          
          <!-- 入库申请时显示容量信息 -->
          <template v-if="!isOutbound">
            <el-table-column label="容量" prop="capacity" width="100" />
            <el-table-column label="已用容量" prop="usedCapacity" width="100" />
            <el-table-column label="剩余容量" width="100">
              <template #default="scope">
                {{ calculateRemainingCapacity(scope.row) }}
              </template>
            </el-table-column>
          </template>
          
          <el-table-column label="状态" prop="status" width="100">
            <template #default="scope">
              <dict-tag :options="wms_location_status" :value="scope.row.status"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button type="primary" link @click.stop="confirmSelection(scope.row)">选择</el-button>
              <!-- 出库场景添加查看库存按钮 -->
              <el-button v-if="isOutbound" type="primary" link @click.stop="showInventory(scope.row)">
                查看库存
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getLocationList"
        />
      </el-dialog>
      
      <!-- 物料库存详情对话框 -->
      <el-dialog
        v-model="inventoryDialogVisible"
        title="库位物料库存详情"
        width="700px"
        append-to-body
      >
        <div v-if="currentLocation">
          <div class="info-header">
            <h3>{{ currentLocation.locationName }} - 库存信息</h3>
            <p>所属仓库: {{ currentLocation.warehouseName }}</p>
          </div>
          
          <el-table :data="inventoryList" v-loading="inventoryLoading">
            <el-table-column label="物料" prop="materialName" width="150" />
            <el-table-column label="物料编码" prop="materialCode" width="120" />
            <el-table-column label="规格型号" prop="specification" width="120" />
            <el-table-column label="库存数量" prop="quantity" width="100" />
            <el-table-column label="单位" prop="unit" width="80" />
            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button type="primary" link @click="selectMaterial(scope.row)">选择</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="empty-block" v-if="inventoryList.length === 0">
            <el-empty description="该库位下暂无库存" />
          </div>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, watch, defineProps, defineEmits } from 'vue';
  import { listLocation } from '@/api/wms/location';
  import { listInventory } from '@/api/mwm/inventory';
  import { listMaterial } from '@/api/mwm/material'; // 修改为使用listMaterial而不是getMaterial
  
  const props = defineProps({
    title: {
      type: String,
      default: '选择库位'
    },
    visible: {
      type: Boolean,
      default: false
    },
    // 是否是出库申请
    isOutbound: {
      type: Boolean,
      default: false
    },
    // 预选仓库ID
    preSelectedWarehouseId: {
      type: [Number, String],
      default: null
    }
  });
  
  const emit = defineEmits(['update:visible', 'select', 'selectWithMaterial']);
  
  // 数据部分
  const locationList = ref([]);
  const warehouseOptions = ref([]);
  const visible = ref(false);
  const loading = ref(false);
  const total = ref(0);
  
  // 物料库存相关
  const inventoryDialogVisible = ref(false);
  const inventoryList = ref([]);
  const currentLocation = ref(null);
  const inventoryLoading = ref(false);
  
  const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    warehouseId: null,
    locationCode: null,
    locationName: null,
    status: '0' // 默认查询正常状态的库位
  });
  
  // 监听visible变化
  watch(() => props.visible, (val) => {
    visible.value = val;
    if (val) {
      // 设置预选仓库
      if (props.preSelectedWarehouseId) {
        queryParams.warehouseId = props.preSelectedWarehouseId;
      }
      getLocationList();
    }
  });
  
  // 监听内部visible变化
  watch(() => visible.value, (val) => {
    emit('update:visible', val);
  });
  
  // 获取库位列表
  function getLocationList() {
    loading.value = true;
    listLocation(queryParams).then(response => {
      locationList.value = response.rows || [];
      total.value = response.total || 0;
      loading.value = false;
    }).catch(() => {
      loading.value = false;
    });
  }
  
  // 处理仓库变更
  function handleWarehouseChange() {
    getLocationList();
  }
  
  // 计算剩余容量
  function calculateRemainingCapacity(location) {
    const capacity = parseFloat(location.capacity) || 0;
    const usedCapacity = parseFloat(location.usedCapacity) || 0;
    return Math.max(0, capacity - usedCapacity).toFixed(2);
  }
  
  // 重置查询条件
  function resetQuery() {
    queryParams.locationCode = null;
    queryParams.locationName = null;
    // 不重置仓库，保持当前选择
    getLocationList();
  }
  
  // 显示库存详情
  function showInventory(location) {
    currentLocation.value = location;
    inventoryDialogVisible.value = true;
    loadInventory(location.locationId);
  }
  
  // 加载库存
  function loadInventory(locationId) {
    inventoryLoading.value = true;
    listInventory({ locationId: locationId }).then(async response => {
      // 获取基本库存数据
      const inventoryData = response.rows || [];
      
      // 如果有库存数据，补充物料信息
      if (inventoryData.length > 0) {
        try {
          // 创建一个物料ID到物料信息的映射
          const materialIds = [...new Set(inventoryData.map(item => item.materialId).filter(id => id != null))];
          const materialMap = new Map();
          
          // 获取所有物料
          const materialResponse = await listMaterial();
          if (materialResponse.code === 200 && materialResponse.rows) {
            materialResponse.rows.forEach(material => {
              if (materialIds.includes(material.materialId)) {
                materialMap.set(material.materialId, material);
              }
            });
          }
          
          // 为每个库存项补充物料信息
          inventoryList.value = inventoryData.map(item => {
            // 确保物料ID存在，过滤掉无效数据
            if (!item.materialId) {
              console.warn("发现物料ID为空的库存记录，已跳过", item);
              return null;
            }
            
            const materialInfo = materialMap.get(item.materialId) || {};
            return {
              ...item,
              materialId: item.materialId, // 确保materialId存在
              materialCode: item.materialCode || materialInfo.materialCode || '',
              materialName: item.materialName || materialInfo.materialName || '',
              specification: item.specification || materialInfo.specification || '',
              unit: item.unit || materialInfo.unit || ''
            };
          }).filter(item => item !== null); // 过滤掉无效数据
        } catch (err) {
          console.error("补充物料信息失败:", err);
          // 确保每个项都有必要的字段
          inventoryList.value = inventoryData.filter(item => item.materialId).map(item => ({
            ...item,
            materialCode: item.materialCode || '',
            materialName: item.materialName || '',
            specification: item.specification || '',
            unit: item.unit || ''
          }));
        }
      } else {
        inventoryList.value = [];
      }
      
      inventoryLoading.value = false;
    }).catch(() => {
      inventoryLoading.value = false;
      inventoryList.value = [];
    });
  }
  
  // 选择物料
  function selectMaterial(material) {
    // 确保物料数据完整
    if (!material.materialId) {
      proxy.$modal.msgError("物料数据不完整，无法选择");
      return;
    }
    
    // 确保所有必要的字段都存在
    const completeData = {
      location: currentLocation.value,
      material: {
        ...material,
        materialId: material.materialId,
        materialCode: material.materialCode || '',
        materialName: material.materialName || '',
        specification: material.specification || '',
        unit: material.unit || '',
        quantity: material.quantity || 0
      }
    };
    
    emit('selectWithMaterial', completeData);
    inventoryDialogVisible.value = false;
    visible.value = false; // 选择物料后关闭库位选择对话框
  }

  // 确认选择库位
  function confirmSelection(location) {
    emit('select', location);
    visible.value = false;
  }

  // 处理点击行选择
  function handleLocationSelect(row) {
    if (!props.isOutbound) {
      confirmSelection(row);
    }
  }

  // 获取字典数据
  import { getCurrentInstance } from 'vue';
  const { proxy } = getCurrentInstance();
  const { wms_location_status } = proxy.useDict('wms_location_status');

  // 初始化仓库列表
  import { listWarehouse } from '@/api/wms/location';
  
  // 组件挂载时获取仓库列表
  import { onMounted } from 'vue';
  onMounted(() => {
    // 获取所有仓库
    listWarehouse().then(response => {
      warehouseOptions.value = response.data || response.rows || [];
    });
  });

  // 暴露方法给父组件调用
  defineExpose({
    // 打开选择器
    open(warehouseId) {
      if (warehouseId) {
        queryParams.warehouseId = warehouseId;
      }
      visible.value = true;
      getLocationList();
    },
    // 重置选择器
    reset() {
      queryParams.warehouseId = null;
      queryParams.locationCode = null;
      queryParams.locationName = null;
      queryParams.pageNum = 1;
    }
  });
</script>

<style scoped>
.location-selector {
    background-color: #f0f9eb !important;
}
.info-header {
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 15px;
}
.info-header h3 {
  margin-top: 0;
  margin-bottom: 8px;
  font-size: 16px;
}
.info-header p {
  margin: 5px 0;
  color: #606266;
}
.empty-block {
  margin: 20px 0;
  text-align: center;
}
</style>
    